import React, { Component } from 'react';
import './index.css';

interface FlipperProps {
  oneHour?: boolean;
  halfHour?: boolean;
  duration?: number;
}

interface FlipperState {
  isFlipping: boolean;
  flipType: 'up' | 'down';
  frontTextFromData: number;
  backTextFromData: number;
}

class Flipper extends Component<FlipperProps, FlipperState> {
  static defaultProps = {
    oneHour: false,
    halfHour: false,
    duration: 600
  };

  constructor(props: FlipperProps) {
    super(props);
    this.state = {
      isFlipping: false,
      flipType: 'down',
      frontTextFromData: 0,
      backTextFromData: 1
    };
  }

  private _textClass(number: number): string {
    return 'number' + number;
  }

  private _thisTimeClass(): string {
    const { oneHour, halfHour } = this.props;
    return (halfHour ? 'digital30 ' : '') + (oneHour ? 'digital60 ' : ' ');
  }

  private _flip(type: 'up' | 'down', front: number, back: number): void {
    if (this.state.isFlipping) {
      return;
    }
    this.setState({
      frontTextFromData: front,
      backTextFromData: back,
      flipType: type,
      isFlipping: true
    });
    setTimeout(() => {
      this.setState({
        frontTextFromData: back,
        isFlipping: false
      });
    }, this.props.duration);
  }

  public flipDown(front: number, back: number): void {
    this._flip('down', front, back);
  }

  public flipUp(front: number, back: number): void {
    this._flip('up', front, back);
  }

  public setFront(text: number): void {
    this.setState({
      frontTextFromData: text
    });
  }

  public setBack(text: number): void {
    this.setState({
      backTextFromData: text
    });
  }

  render() {
    const { isFlipping, flipType, frontTextFromData, backTextFromData } = this.state;
    return (
      <div className={['M-Flipper', flipType, isFlipping ? 'go' : null].join(' ')}>
        <div
          className={`digital front ${this._thisTimeClass()}${this._textClass(frontTextFromData)}`}
        />
        <div
          className={`digital back ${this._thisTimeClass()}${this._textClass(backTextFromData)}`}
        />
      </div>
    );
  }
}

export default Flipper; 